package com.wellsoft.mobileoa.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;

import org.androidpn.client.Constants;
import org.androidpn.client.NotificationDetailsActivity;
import org.androidpn.client.ServiceManager;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.wellsoft.mobileoa.LoginActivity;
import com.wellsoft.mobileoa.NotifyDetailActivity;
import com.wellsoft.mobileoa.R;
import com.wellsoft.mobileoa.dbmodel.ContactInfo;
import com.wellsoft.mobileoa.wsmodel.WSOA_Action;
import com.wellsoft.mobileoa.wsmodel.WSOA_Cookie;
import com.wellsoft.mobileoa.wsmodel.WSOA_Login_Request;
import com.wellsoft.mobileoa.wsmodel.WSOA_Login_Response;
import com.wmobile.utils.BaseObject;
import com.wmobile.utils.CommUtils;
import com.wmobile.utils.ServiceResponse;
import com.wmobile.utils.comm.Webservice;

public class SystemConfig {
	private static final Random random = new Random(System.currentTimeMillis());

	private static String goBackUrl;
	private static String goBackTargetUrl;

	private static CommUtils service;
	private static List<WSOA_Cookie> cookies;
	public static List<BaseActivity> activityStack;
	// 当前登录的用户名密码
	private static String userName;
	private static String password;
	private static String deviceId;
	// 系统默认登录的用户名密码
	private final static String USERINFOSP = "USERINFO";

	public static void saveServerUrl(String serverUrl) {
		if (stringIsNullOrEmpty(serverUrl))
			return;
		SharedPreferences sp = getCurrentActivity().getSharedPreferences(
				USERINFOSP, 0);
		sp.edit().putString("SERVERURL", serverUrl).commit();
	}

	public static String readServerUrl() {
		SharedPreferences sp = getCurrentActivity().getSharedPreferences(
				USERINFOSP, 0);
		String serverUrl = sp.getString("SERVERURL", "oa.well-soft.com:6000");
		return serverUrl;
	}

	public static void saveIsRememberUserName(boolean isRememberUserName) {
		SharedPreferences sp = getCurrentActivity().getSharedPreferences(
				USERINFOSP, 0);
		if (isRememberUserName) {
			sp.edit().putString("ISREMEMBERUSERNAME", "Y").commit();
		} else {
			sp.edit().putString("ISREMEMBERUSERNAME", "N").commit();
		}
	}

	public static boolean readIsRememberUserName() {
		SharedPreferences sp = getCurrentActivity().getSharedPreferences(
				USERINFOSP, 0);
		String isRememberUserName = sp.getString("ISREMEMBERUSERNAME", "Y");
		if (isRememberUserName.equals("Y")) {
			return true;
		} else {
			return false;
		}
	}

	public static void saveIsRememberPassword(boolean isRememberPassword) {
		SharedPreferences sp = getCurrentActivity().getSharedPreferences(
				USERINFOSP, 0);
		if (isRememberPassword) {
			sp.edit().putString("ISREMEMBERPASSWORD", "Y").commit();
		} else {
			sp.edit().putString("ISREMEMBERPASSWORD", "N").commit();
		}
	}

	public static boolean readIsRememberPassword() {
		SharedPreferences sp = getCurrentActivity().getSharedPreferences(
				USERINFOSP, 0);
		String isRememberPassword = sp.getString("ISREMEMBERPASSWORD", "N");
		if (isRememberPassword.equals("Y")) {
			return true;
		} else {
			return false;
		}
	}

	public static void saveRememberedUserName(String userName) {
		SharedPreferences sp = getCurrentActivity().getSharedPreferences(
				USERINFOSP, 0);
		sp.edit().putString("REMEMBEREDUSERNAME", userName).commit();
	}

	public static String readRememberedUserName() {
		SharedPreferences sp = getCurrentActivity().getSharedPreferences(
				USERINFOSP, 0);
		String userName = sp.getString("REMEMBEREDUSERNAME", "");
		return userName;
	}

	public static void saveRememberedPassword(String userPwd) {
		SharedPreferences sp = getCurrentActivity().getSharedPreferences(
				USERINFOSP, 0);
		sp.edit().putString("REMEMBEREDPASSWORD", userPwd).commit();
	}

	public static String readRememberedPassword() {
		SharedPreferences sp = getCurrentActivity().getSharedPreferences(
				USERINFOSP, 0);
		String password = sp.getString("REMEMBEREDPASSWORD", "");
		return password;
	}

	public static String getDeviceId() {
		return deviceId;
	}

	public static void setDeviceId(String deviceId) {
		SystemConfig.deviceId = deviceId;
	}

	public static String getPassword() {
		return password;
	}

	public static void setPassword(String password) {
		SystemConfig.password = password;
	}

	public static String getUserName() {
		return userName;
	}

	public static void setUserName(String userName) {
		SystemConfig.userName = userName;
	}
	/**
	 * 联系人信息
	 */
	private static List<ContactInfo> contactList;

	public static List<ContactInfo> getContactList() {
		return contactList;
	}

	public static void setContactList(List<ContactInfo> contactList) {
		SystemConfig.contactList = contactList;
	}

	private static List<String> opinions;

	public static List<String> getOpinions() {
		return opinions;
	}

	public static void setOpinions(List<String> opinions) {
		SystemConfig.opinions = opinions;
	}

	public static String getGoBackUrl() {
		return goBackUrl;
	}

	public static void setGoBackUrl(String goBackUrl) {
		SystemConfig.goBackUrl = goBackUrl;
	}

	public static String getGoBackTargetUrl() {
		return goBackTargetUrl;
	}

	public static void setGoBackTargetUrl(String goBackTargetUrl) {
		SystemConfig.goBackTargetUrl = goBackTargetUrl;
	}

	public static BaseActivity getCurrentActivity() {
		// Log.v("getcount", activityStack.size() + "");
		return activityStack.get(activityStack.size() - 1);
	}

	public static BaseActivity getPreviousActivity() {
		// Log.v("getcount", activityStack.size() + "");
		return activityStack.get(activityStack.size() - 2);
	}

	public static int getActivityStackCount() {
		// Log.v("getcount", activityStack.size() + "");
		return activityStack.size();
	}

	public static void pushActivity(BaseActivity baseActivity) {
		if (activityStack == null) {
			activityStack = new ArrayList<BaseActivity>();
		}
		activityStack.add(baseActivity);
		// Log.v("getcount", activityStack.size() + "");
	}

	public static void popActivity() {
		if (activityStack == null) {
			activityStack = new ArrayList<BaseActivity>();
		}
		if (activityStack.size() > 0) {
			activityStack.remove(activityStack.size() - 1);
		}
		Log.v("getcount", activityStack.size() + "");
	}

	/**
	 * 系统标准日期格式
	 */
	public static SimpleDateFormat dateSdf = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 系统标准时间格式
	 */
	public static SimpleDateFormat timeSdf = new SimpleDateFormat("HH:mm:ss");

	public static SimpleDateFormat datetimeSdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm");

	/**
	 * 系统固定时间格式
	 */
	public static SimpleDateFormat stdSdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	public static void init(BaseActivity baseActivity) {

		if (service == null) {
			service = new Webservice(
					"http://oa.well-soft.com:8086/wsoaservice/MobileOAService.asmx",
					"http://mobileoa.well-soft.com/", true);
			// "http://192.168.1.105/WSOAMOBIMIDWARE/MobileOAService.asmx",
			// "http://mobileoa.well-soft.com/", true);
		}

		// Start the service
		ServiceManager.setSysNotifyListener(sysNotifyListener);
		ServiceManager serviceManager = new ServiceManager(baseActivity);
		serviceManager.setNotificationIcon(R.drawable.ic_launcher);
		serviceManager.startService();
	}

	public static void resetWebService(String url) {
		service = new Webservice(url, "ttp://mobileoa.well-soft.com/", true);
	}

	public static CommUtils getService() {
		return service;
	}

	public static boolean stringIsNullOrEmpty(String s) {
		if (s == null || s.length() <= 0)
			return true;
		else
			return false;
	}

	public static boolean isInt(String s) {
		if (s == null || s.length() == 0)
			return false;
		Pattern pattern = Pattern.compile("^[+-]?\\d*$");
		return pattern.matcher(s).matches();
	}

	public static boolean IsUnsign(String s) {
		if (s == null || s.length() == 0)
			return false;
		Pattern pattern = Pattern.compile("^\\d*[.]?\\d*$");
		return pattern.matcher(s).matches();
	}

	public static boolean isNumberic(String s) {
		if (s == null || s.length() == 0)
			return false;
		Pattern pattern = Pattern.compile("^[+-]?\\d*[.]?\\d*$");
		return pattern.matcher(s).matches();
	}

	public static boolean isUnsignNumberic(String s) {
		if (s == null || s.length() == 0)
			return false;
		Pattern pattern = Pattern.compile("^\\d*[.]?\\d*$");
		return pattern.matcher(s).matches();
	}

	public static List<WSOA_Cookie> getCookies() {
		return cookies;
	}

	public static void setCookies(List<WSOA_Cookie> cookies) {
		SystemConfig.cookies = cookies;
	}

	public static boolean reLogin() {
		Date date = new Date();
		try {
			if (date.after(SystemConfig.dateSdf.parse("2014-01-15"))) {
				return false;
			}
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
		Map<String, BaseObject> requests = new HashMap<String, BaseObject>();

		WSOA_Login_Request login_Request = new WSOA_Login_Request();
		login_Request.setUsername(SystemConfig.getUserName());
		login_Request.setPassword(SystemConfig.getPassword());
		login_Request.setDeviceType("AND");
		login_Request.setDeviceToken(SystemConfig.getDeviceId());

		requests.put("request", login_Request);
		ServiceResponse response = SystemConfig.getService()
				.CallserviceOnMainThread(requests, "WSOA_Login",
						WSOA_Login_Response.class);

		if (!response.getExeFlag()) {
			return false;
		}
		WSOA_Login_Response login_response = (WSOA_Login_Response) response
				.getResponseData();
		if (login_response.getExeFlag() == 0) {
			return false;
		}
		SystemConfig.setUserName(SystemConfig.getUserName());
		SystemConfig.setPassword(SystemConfig.getPassword());
		SystemConfig.setCookies(login_response.getCookies());
		return true;
	}

	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static OnSystemNotifyListener sysNotifyListener = new OnSystemNotifyListener() {

		@Override
		public void onGetDeviceId(String deviceId) {
			SystemConfig.setDeviceId(deviceId);
		}

		@Override
		public void onNotified(String title, String message, String url,
				Notification notification) {
			if (SystemConfig.stringIsNullOrEmpty(SystemConfig.getUserName())) {
				return;
			}
			BaseActivity baseActivity = SystemConfig.getCurrentActivity();
//			baseActivity.showMessage(url);
			boolean isBackground = isBackgroundActivity(baseActivity);
			if (isBackground) {
				NotificationManager notificationManager = (NotificationManager) baseActivity
						.getSystemService(Context.NOTIFICATION_SERVICE);

				Intent intent = new Intent(baseActivity,
						NotifyDetailActivity.class);
				intent.putExtra(Constants.NOTIFICATION_TITLE, title);
				intent.putExtra(Constants.NOTIFICATION_MESSAGE, message);
				intent.putExtra(Constants.NOTIFICATION_URI, url.replace("%26", "&"));
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
				intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
				intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

				PendingIntent contentIntent = PendingIntent.getActivity(
						baseActivity, 0, intent,
						PendingIntent.FLAG_UPDATE_CURRENT);

				notification.setLatestEventInfo(baseActivity, title, message,
						contentIntent);
				notificationManager.notify(random.nextInt(), notification);
			} else {
				final String tmpUrl = url.replace("%26", "&");
				final BaseActivity tmpBaseActivity = baseActivity;
				baseActivity.showAlertDialog(baseActivity, message, null,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								WSOA_Action wsAction = new WSOA_Action();
								wsAction.setFuncType("0");
								wsAction.setUrl(tmpUrl);

								ServiceResponse response = BaseAction
										.executeActions(null, wsAction,
												tmpBaseActivity.getBaseView());
								if (!response.getExeFlag()) {
									tmpBaseActivity.showMessage(response
											.getMessage());
									return;
								}
							}
						}, onCancelListener);
			}
		}
	};

	protected static boolean isBackgroundActivity(Activity activity) {
		String packageName = LoginActivity.class.getName().replace(
				"." + LoginActivity.class.getSimpleName(), "");
		ActivityManager activityManager = (ActivityManager) activity
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
		if (tasksInfo.size() > 0) {
			// 应用程序位于堆栈的顶层
//			SystemConfig.getCurrentActivity().showMessage(packageName+" "+tasksInfo.get(0).topActivity
//					.getPackageName());
			if (packageName.equals(tasksInfo.get(0).topActivity
					.getPackageName())) {
				return false;
			}
		}
		return true;
	}

	public static DialogInterface.OnClickListener onCancelListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss();
		}
	};
}